/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-05-30 04:52:44
 * @modify date 2017-05-30 04:52:44
 * @desc [description]
*/

global.Promise = require('bluebird')
const Conf = require('./config/config')
const Koa = require('koa')
const app = new Koa()
const logger = require('koa-logger')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const static = require('koa-static')
const database = require('./config/database')
// 全局错误处理
app.use( async ( ctx, next ) => {
  try {
    await next()
  } catch ( err ) {
    ctx.body = err.message
    ctx.status = err.status || 500
  }
})
app.use(logger())
app.use(bodyParser())
app.use(static(__dirname + '/static'))
try {
  database.connect()
} catch (error) {
  ctx.throw('数据库链接失败', 500)
}


/**
 * 路由
 */

const api = require('./routes/api')
const web = require('./routes/web')
app.use(api.routes())
app.use(web.routes())
app.listen(Conf.port, () => {
  console.log(`serve is runing at port ${Conf.port}`)
})
app.on('error', (err) => {
  console.error(err)
})
module.exports = app
